<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>伪网站-登录</title>
  <link rel="stylesheet" href="../CSS/登录.css">
</head>

<body>

  <h1>登录页面</h1>

  <form>
    <span>用户名密码错误, 请重试 ! ^_^</span>
    <label>
      用户名: <input class="name" type="text">
    </label>
    <label>
      密码: <input class="pwd" type="password">
    </label>
    <label for="">
      <a href="./注册.html">没有账号？点击注册</a>
    </label>
    <button>登录</button>
  </form>
  <script src="../axios.min.js"></script>
  <script src="../http.js"></script>
  <script>
    /*
      登录
        - 获取元素
        - 给表单绑定一个表单提交事件
          + 获取输入的表单数据
            - 数据校验
              + 不为空校验
          + 请求服务器接口校验登录
            - 注意: 默认登录用户信息
              - 用户名: admin
              - 密码: 123456
    */
    //  获取元素
    let form = document.querySelector('form');
    let nameInp = document.querySelector('.name');
    let pwdInp = document.querySelector('.pwd');
    let errBox = document.querySelector('span');

    form.addEventListener('submit', async function (event) {
      // 阻止表单默认提交 阻止浏览器默认行为
      event.preventDefault();
      // console.log('666');
      let username = nameInp.value;
      let password = pwdInp.value;
      if (!username || !password) return alert('请完整填写表单')

      let res = await http.post('/users/login', { username: username, password: password })
      console.log(res.data)
      if (res.data.code != 1) {
        errBox.style.display = 'block';
        return;
      }

      alert('登录成功');
      // 将token和用户id存储到本地
      localStorage.setItem('token', res.data.token);
      localStorage.setItem('uid', res.data.user.id);
      location.href = "./首页.html"
    })

  </script>
</body>

</html>